import type { ProColumns } from '@ant-design/pro-components';
import {ActionType, EditableProTable, nanoid, PageContainer, ProForm, ProFormText} from '@ant-design/pro-components';
import {
  Form,
  message,
  Card,
  Typography,
  Row,
  Col,
  Space,
  Dropdown,
  Popconfirm,
  Button,
  Menu,
  DatePicker,
  Upload, Modal
} from 'antd';
import React, {useRef, useState} from 'react';
import { history } from 'umi';
import {
  DisciInfluenceApi,
  DownloadApi,
  FillApi, GetSaveApi, SaveApi,
  SchoolCheckShow,
  ShowApi,
  UploadApi
} from "@/services/School/SchoolApi";
import {ServerMessages} from "@/services/ServerMessages";
import {getYearFromRange, getYearFromRangeShit, ShowError} from "@/utils/format";
import {DownloadOutlined, UploadOutlined} from "@ant-design/icons";
import Submitter from "@/pages/Syl/Common/Submitter";
import moment from "moment";
const locale = undefined

const { Text } = Typography;


type DataSourceType = {
  id: React.Key;
  tch_name?: string;
  ac_org?: string;
  pos?: string;
  tenure?: string;
};

const defaultData: DataSourceType[] = [
  {
    id: nanoid(),
    tch_name: '',
    ac_org: '',
    pos: undefined,
    tenure: '',
  },
];

const columns: ProColumns<DataSourceType>[] = [
  {
    title: '教师姓名',
    dataIndex: 'tch_name',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '学术组织名称',
    dataIndex: 'ac_org',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '担任职务',
    dataIndex: 'pos',
    valueEnum: {
      '会长': '会长',
      '副会长': '副会长',
      '理事长': '理事长',
      '副理事长': '副理事长',
      '秘书长': '秘书长',
      '副秘书长': '副秘书长',
    },
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
  },
  {
    title: '任职期限(在职选择当前日期)',
    dataIndex: 'tenure',
    formItemProps: () => {
      return {
        rules: [{ required: true, message: '此项为必填项' }]
      };
    },
    renderFormItem: () => <DatePicker.RangePicker picker="month" />,
  },
  {
    title: '操作',
    valueType: 'option',
  },
];

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const [dataSource, setDataSource] = useState<DataSourceType[]>(() => defaultData);
  const [editForm] = Form.useForm()
  const download = '3_3_2'
  const status_is_show = history.location.query.flag === 'display'
  const status_is_check = history.location.query.id && history.location.query.fill_id
  const actionRef = useRef<ActionType>();
  const handleSaveBtn = () => {
    console.log("@Save", download)
    const data = {
      fill_id: download,
      data: dataSource
    }
    console.log("@请求数据", data)
    SaveApi('/api/temp-save', data).then(response => {
      if (response.status === 0) {
        Modal.success({
          title: <span>保存成功！</span>,
          onOk() {
            window.location.reload()
          }
        })
      } else {
        ShowError(response.message)
      }
    }, () => {
      ShowError(ServerMessages.error_message)
    })
  }

  const upload = UploadApi('/api/index/teacher-team/International-level/conference-director-template',
    (info) => {
      console.log("@success", info)
      if (info.file.response.status === 0) {
        const data = info.file.response.data["data_"+download]
        for (let i = 0; i < data.length; i++) {
          data[i].id = nanoid()
          data[i].tenure = [moment(data[i].tenure.split('至')[0], 'YYYY-MM'), moment(data[i].tenure.split('至')[1], 'YYYY-MM')]
        }
        setDataSource(data)
        var id_arr = []
        for (let i = 0; i < data.length; i++) {
          id_arr.push(data[i].id)
        }
        setEditableRowKeys(id_arr)
      } else {
        ShowError(info.file.response.message)
      }
    })

  return (
    <PageContainer
      title="教师在国内外重要学术会议组织任职主要负责人清单"
      content={<Typography.Text type="danger">1. 监测点内涵：2021年1月1日至今，各年度，学科教师在国内外重要学术组织担任正副负责人和秘书长的情况。
        <br/>2. 学术组织：在学术领域或专业领域进行国际合作而成立的国际性机构，如国际地球化学学会、国际体育舞蹈协会等；也包括我国在民政局注册的和在中国科协注册的国家一级学会。
        <br/>3. 任职期限：任职起止年月，如2007-08至2016-11。
        <br/>4. 担任职务：会长、副会长、理事长、副理事长、秘书长、副秘书长。
        <br/>5. 仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。
    </Typography.Text>}>
      <Card bordered={false}>
        <ProForm
          onFinish={async () => {
            if (dataSource.length === 0) {
              message.warn("请输入内容")
              return {}
            }
            return new Promise((resolve => {
              editForm.validateFields().then(() => {

                for (let i = 0; i < dataSource.length; i++) {
                  dataSource[i].tenure = getYearFromRangeShit(dataSource[i].tenure)
                }

                const dataObj = {
                  'data_3_3_2': dataSource
                }
                console.log('@请求数据', dataObj)

                FillApi('/api/index/teacher-team/International-level/conference-director',
                  dataObj, (response) => {
                    message.success(response.message)
                    history.push('/teacher-team/international-level')
                    resolve(true)
                  }, (response) => {
                    ShowError(response.message)
                    resolve(false)
                  }, () => {
                    ShowError(ServerMessages.error_message)
                    resolve(false)
                  })

              }, () => {
                resolve(false)
              })
            }))
          }}
          submitter={{
            render: (props, doms) => {
              return <Submitter
                upload={upload}
                download={download}
                doms={doms}
                save={handleSaveBtn}
              />
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            submitButtonProps: {
              style: {
                marginLeft: '-8px'
              }
            },
          }}
        >
          <EditableProTable<DataSourceType>
            pagination={{
              pageSize: 10
            }}
            value={dataSource}
            onChange={setDataSource}
            actionRef={actionRef}
            columns={columns}
            request={async () => {

              // 如果是审核或者查看,则异步加载内容
              return new Promise(resolve => {
                if (status_is_check) {
                  // 审核时加载内容
                  SchoolCheckShow(history.location.query.id, history.location.query.fill_id)
                    .then(response => {
                      console.log(response)
                      if (response.status === 0) {
                        for (let i = 0; i < response.message.length; i++) {
                          response.message[i].id = nanoid()
                          // response.message[i].tenure = response.message[i].tenure
                          //   ? [
                          //     moment(String(response.message[i].tenure[0]), 'YYYY-MM'),
                          //     moment(String(response.message[i].tenure[1]), 'YYYY-MM'),
                          //   ]
                          //   : undefined;

                        }
                        resolve({data: response.message})
                      } else {
                        resolve(true)
                      }
                    })
                } else if (status_is_show) {
                  // 查看时加载内容
                  ShowApi(download).then(response => {
                    console.log("@response", response)
                    if (response.status === 0) {
                      resolve({data: response.data})
                    }
                  })
                  // resolve(true)
                } else {
                  // resolve({data: dataSource})
                  GetSaveApi('/api/show-temp-save', download).then(response => {
                    console.log("@response", response)
                    if (response.status === 0) {
                      for (let i = 0; i < response.data.length; i++) {
                        response.data[i].id = nanoid()
                        response.data[i].tenure = response.data[i].tenure
                          ? [
                            moment(String(response.data[i].tenure[0]), 'YYYY-MM'),
                            moment(String(response.data[i].tenure[1]), 'YYYY-MM'),
                          ]
                          : undefined;

                      }
                      resolve({data: response.data})
                      setDataSource(response.data);
                      var id_arr = []
                      for (let i = 0; i < response.data.length; i++) {
                        id_arr.push(response.data[i].id)
                      }
                      setEditableRowKeys(id_arr)
                    } else {
                      resolve({data: dataSource})
                    }
                  })
                }
              })
            }}
            rowKey="id"
            recordCreatorProps={{
              newRecordType: 'dataSource',
              record: () => ({
                id: nanoid(),
              }),
              style: {
                display: status_is_show || status_is_check ? 'none' : 'block',
              },
            }}
            editable={{
              type: 'multiple',
              form: editForm,
              editableKeys,
              actionRender: (row, config, defaultDoms) => {
                return [defaultDoms.delete];
              },
              onValuesChange: (record, recordList) => {
                if (record) {
                  setDataSource(recordList);
                } else {
                  // recordList 代表表单的真实数据，但是在空值检测时会变成空值，
                  // 所以只在有输入变化时同步到 DataSource，可以通过 record 来判断是否有输入。
                  // 执行删除操作时，DataSource 应该删掉 recordList 中不存在的项目。
                  let index_list = []
                  for (let i = 0; i < recordList.length; i++) {
                    index_list.push(recordList[i].id)
                  }
                  let newDataSource = []
                  for (let i = 0; i < dataSource.length; i++) {
                    if (index_list.indexOf(dataSource[i].id) !== -1) {
                      newDataSource.push(dataSource[i])
                    }
                  }
                  setDataSource(newDataSource)
                }
              },
              onChange: setEditableRowKeys,
            }}
            style={{marginBottom: 20}}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};

